package org.example;

import java.util.concurrent.locks.ReentrantLock;

/**
 * the type of ${PROJECT_NAME}
 *
 * <p> lock 三部曲：
 *  new ReentrantLock（）
 *  lock.lock()
 *  解锁 finally， lock.unlock()
 * .
 *
 * @author 铁甲小宝
 * @date ${YEAR}-${MONTH}-${DAY}
 */
public class JUCXXReentrantLock {

    private static int num = 30;
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {for (int i = 0; i < 40; i++) {
            sale();
        }
        },"A").start();
        new Thread(() -> {for (int i = 0; i < 40; i++) {
            sale();
        }
        },"B").start();
        new Thread(() -> {for (int i = 0; i < 40; i++) {
            sale();
        }
        },"C").start();
    }


    public static void sale(){
        lock.lock();
        try {
            //业务代码
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (num--) + "张票，剩余" + num + "张");
            }
        }finally {
            lock.unlock();
        }
    }
}